package com.ruoyi.framework.mqtt.handler;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.project.instrument.domain.InsAlarmRecord;
import com.ruoyi.project.instrument.service.IInsAlarmRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author Taney
 */
@Component
public class InstrumentAlarmHandler extends AbstractHandler {

    public static final String TOPIC = "/event/deviceAlarm";

    @Autowired
    IInsAlarmRecordService alarmRecordService;

    @Override
    public void handleMessage(Message message, String topic, String msg) throws MessagingException {
        if (matches(TOPIC, topic)) {
            ClientInfo clientInfo = getClientInfo(topic);
            String product = clientInfo.getProduct();
            String deviceId = clientInfo.getDeviceId();
            logger.debug("设备[{}-{}]报警日志【{}】", product, deviceId, msg);
            /*
            {
            "level":1,
            "alarmTime":100000000,//报警时间=>时间戳（毫秒）,
            "alarmCode":30101,//错误码,
            "alarmDesc":"样本针运动异常"//报警详细内容
            }
             */
            if (isJson(msg)) {
                JSONObject jsonObject = JSONUtil.parseObj(msg);
                InsAlarmRecord insAlarmRecord = new InsAlarmRecord();
                insAlarmRecord.setLevel(jsonObject.getStr("level"));
                insAlarmRecord.setAlarmTime(new Date(jsonObject.getLong("alarmTime")));
                insAlarmRecord.setCode(jsonObject.getLong("alarmCode"));
                insAlarmRecord.setCuowu(jsonObject.getStr("alarmDesc"));
                alarmRecordService.save(insAlarmRecord);
                reStatistics(deviceId,ALARM,null);
            }
        }
    }
}
